<template>
  <div class="edit_file" v-if="editVisible">
    <div class="file_head">
      <div class="path">{{ editPyPath }}</div>
      <div class="buttons">
        <el-button type="plain" size="small" @click="$emit('update:editVisible', false)"
          >取 消</el-button
        >
        <el-button type="primary" size="small" @click="saveFile()">保 存</el-button>
      </div>
    </div>
    <div class="editor-content">
      <data-code-editor ref="pyfile" :value="pyContent" @input="updateContent" />
    </div>
  </div>
</template>
<script>
import DataCodeEditor from "../../data/components/data-code-editor";
export default {
  name: "editFile",
  components: {
    DataCodeEditor
  },
  props: {
    editPyPath: {
      type: String,
      default: ""
    },
    editVisible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      pyContent: ""
    };
  },

  methods: {
    updateContent(content) {
      this.pyContent = content;
    },
    saveFile() {
      var blob = new Blob([this.pyContent]);
      var arr = this.editPyPath.split("/");
      var fileName = arr[arr.length - 1];
      var filePath = this.editPyPath.replace(fileName, "");
      const file = new window.File([blob], fileName);
      let token = this.$cookies.get("token")
      let fd = new FormData();
      fd.append("file", file); //文章中取的值是 file.raw
      fd.append("size", blob.size);
      fd.append("path", filePath);

      axios({
        method: "post",
        url: "/api/idata/files/upload",
        headers: {
          "Content-Type": "multipart/form-data",
          "Authorization": token
        },
        data: fd
      }).then(res => {
        this.$emit("update:editVisible", false);
        this.$message({
          message: "文件成功",
          type: "success"
        });
      });
    }
  },

  watch: {
    editPyPath(val) {
      this.$http.managefiles.readFile({ file_path: val }).then(res => {
        this.pyContent = res;
        this.$refs.pyfile.setValue(this.pyContent);
      }).catch(err => {
        this.pyContent = '';
        this.$refs.pyfile.setValue(this.pyContent);
      })
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/.editor-content .CodeMirror {
  height: 100% !important;
}
.edit_file {
  height: 100%;
  .file_head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .path {
      font-size: 16px;
      color: #409eff;
    }
  }
  .editor-content {
    margin-top: 15px;
    height: calc(100% - 50px);
    overflow: auto;
    border-top: 1px solid #ddd;
  }
}
</style>
